export class IoComService {


    public port = null;

    public hasOpen = false;
    public reader = null;

    // @ts-ignore
    private async init() {
        if (!('serial' in navigator)) {
            alert('你的浏览器不支持串口连接')
            return
        }
        if (this.port !== null) {
            console.log("串口已经打开了")
            return
        }
        // 获取用户之前授予该网站访问权限的所有串口
        // @ts-ignore
        const [oldPorts] = await Promise.all([navigator.serial.getPorts()])
        if (this.port === null && oldPorts.length > 0) {
            this.port = oldPorts[0]
        } else {
            // 提示用户选择一个串口
            // @ts-ignore
            this.port = await navigator.serial.requestPort()

        }


    }


    // @ts-ignore
    public async onOpen(callback) {
        try {
            if (this.hasOpen) return
            await this.init()
            await this.port.open({
                baudRate: 115200, // 波特率
                dataBits: 8, // 每帧的数据位数(7或8)
                stopBits: 1, // 停止位数(1或2)
                bufferSize: 255,/*缓冲区大小*/
                parity: 'none', // 校验模式，可以是none，偶数，奇数
                flowControl: 'none' // 流控模式(none或hardware)。
            })

            this.hasOpen = true
            callback.value = true


        } catch (e) {
            console.log('设备连接失败' + e.message)
        }
    }


    // 发卡


    public async sendCmd() {
        const sendData = this.strToHex('41 54 2B 47 53 4E 3D 31 0D');
        const writer = this.port.writable.getWriter()
        await writer.write(sendData)
        await writer.releaseLock()

    }




    //转换工具类
    private strToHex(hex: string) {
        const value = hex.replace(/\s+/g, '')
        if (/^[0-9A-Fa-f]+$/.test(value) && value.length % 2 === 0) {
            let data = []
            for (let i = 0; i < value.length; i = i + 2) {
                data.push(parseInt(value.substring(i, i + 2), 16))
            }
            return new Uint8Array([...data, 0x0d, 0x0a])
        } else {
            return null;

        }


    }

    public isNumber(value) {
        return !isNaN(parseFloat(value));
    }

    public async onRead(callback: any) {

        try {
            let result = ''
            const textDecoder = new TextDecoderStream();
            this.port.readable.pipeTo(textDecoder.writable);
            this.reader = textDecoder.readable.getReader();


            while (this.port.readable && this.hasOpen) {

                const {value, done} = await this.reader.read();
                if (done || !this.hasOpen) {
                    // Allow the serial port to be closed later.
                    this.reader.releaseLock();

                    break;
                }
                if (value ) {

                    result = result + value


                    if (value==='K') {

                        callback(result)
                        result = ''
                    }


                }
            }


        } catch (e) {
            console.log(e)
        }
    }


}